//
//  FileUtil.m
//  ToS
//
//  Created by 宁校航 on 15/8/13.
//  Copyright (c) 2015年 宁校航. All rights reserved.
//

#import "FileUtil.h"

#import "MainInterface.h"

@implementation FileUtil

+(NSString *)getFilePath:(NSString *)filePath fileType:(enum FileType)type
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *newPath;
    NSString *pathStr;
    if ([filePath isKindOfClass:[NSDictionary class]]) {
        pathStr = [filePath valueForKey:@"Path"];
    }else if ([filePath isKindOfClass:[NSString class]])
    {
        pathStr = filePath;
    }
    switch (type) {
        case LocalFile:
        {
            newPath = [[WellConfig sharedInstance].localDir stringByAppendingPathComponent:pathStr];
        }
            break;
        default:
        {
            
            newPath = [[WellConfig sharedInstance].homeDir stringByAppendingPathComponent:pathStr];
        }
    }
    
    if(![fileManager fileExistsAtPath:[newPath stringByDeletingLastPathComponent]])
    {
        [fileManager createDirectoryAtPath:[newPath stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    return newPath;
}

+(UIImage *)getAppropriateImage:(UIImage *)img
{
    CGFloat width,height,widthScale,heightScale;
    
    width = img.size.width;
    height = img.size.height;
    widthScale = width/1920;
    heightScale = height/1920;
    
    if (widthScale<1 && heightScale<1) {
        return img;
    }
    else
    {
        if (widthScale>heightScale) {
            width = img.size.width/widthScale;
            height = img.size.height/widthScale;
        }
        else
        {
            width = img.size.width/heightScale;
            height = img.size.height/heightScale;
        }
    }
    
    UIGraphicsBeginImageContext(CGSizeMake(width, height));
    [img drawInRect:CGRectMake(0,0,width,height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    img = nil;
    
    return newImage;
}


+(UIImage *)getAppropriateSizeAndQualityImage:(UIImage *)img
{
    UIImage *newImage=[FileUtil getAppropriateImage:img];
    
    
    NSData *d=UIImageJPEGRepresentation(newImage, 0.8);
    
    return [UIImage imageWithData:d];
}



+(void)deleteFile:(NSString *)file
{
    [[NSFileManager defaultManager] removeItemAtPath:file error:nil];
}

+(void)downLoadFile:(NSString *)name WithType:(NSInteger)type finished:(void (^)(NSInteger finish,NSString *newPath))status
{
    // 异步下载
    __block NSInteger taskStatus = 0;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        if (type == 1 && [[userDefaults valueForKey:@"WiFiPicture"] boolValue] && [WellConfig sharedInstance].currentNetStatus != 2) {
            status(taskStatus,@"");
        }
        else
        {
            NSString *urlStr = [NSString stringWithFormat:@"%@%@",[WellConfig getFileWebAddress],name];
            
            NSString *address = [FileUtil getFilePath:name fileType:DefaultFile];
            
            [MainInterface downloadFileURL:urlStr savePath:address success:^(id responseObject) {
                taskStatus = 1;
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    status(taskStatus,address);
                });
            } fail:^{
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    status(taskStatus,address);
                });
            }];
        }
    });
}

+(void)moveFileFrom:(NSString *)startPath To:(NSString *)endPath
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *moveError = nil;
    
    if(![fileManager fileExistsAtPath:[endPath stringByDeletingLastPathComponent]])
    {
        [fileManager createDirectoryAtPath:[endPath stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
//    [fileManager moveItemAtPath:startPath toPath:endPath error:&moveError];
    [fileManager copyItemAtPath:startPath toPath:endPath error:&moveError];
}

//+(NSString *)changeModels:(NSString *)model WithModelName:(NSString *)modelName AndProjectId:(NSInteger)projectId
//{
//    NSString *newPath = [model stringByDeletingLastPathComponent];
//    newPath = [NSString stringWithFormat:@"%@/%@",newPath,modelName];
//    NSString *newFilePath = [FileUtil getFilePath:newPath fileType:ProjectDefaultFile WithProjectId:projectId];
//    return newFilePath;
//}

+(NSString *)getModelFileAddress:(NSInteger)project WithType:(NSInteger)type
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    NSString *str = @"";
    
    if (type == 1) {
        str = [NSString stringWithFormat:@"ProjectFiles/Models/%@",[NSNumber numberWithInteger:project]];
    }
    else if(type == 2)
    {
        str = [NSString stringWithFormat:@"ProjectFiles/Pictures/%@",[NSNumber numberWithInteger:project]];
    }
    else if (type == 3)
    {
        str = @"SkinFile";
    }
    else
    {
        str = @"ProjectFiles/Models";
    }
    
    NSString *newPath = [[WellConfig sharedInstance].homeDir stringByAppendingPathComponent:str];
    if(![fileManager fileExistsAtPath:newPath])
    {
        [fileManager createDirectoryAtPath:newPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    return newPath;
}

#pragma mark - 解压压缩包
+(BOOL)unzipFile:(NSDictionary *)dic
{
//    NSString *filePath = [dic valueForKey:@"ZipAddress"];
//    NSString *folderPath = [dic valueForKey:@"TargetAddress"];
//
//    ZipArchive* zip = [[ZipArchive alloc] init];
//
//    NSFileManager *fileManager = [NSFileManager defaultManager];
//
//    if(![fileManager fileExistsAtPath:folderPath])
//    {
//        [fileManager createDirectoryAtPath:folderPath withIntermediateDirectories:YES attributes:nil error:nil];
//    }
//
//    if( [zip UnzipOpenFile:filePath] )
//    {
//        BOOL ret = [zip UnzipFileTo:folderPath overWrite:YES];
//        if( NO==ret )
//        {
//            return false;
//        }
//        [zip UnzipCloseFile];
//    }
//
//    [fileManager removeItemAtPath:filePath error:nil];
    
    return true;
}


/**
 检测本地是否存在对应文件
 
 @param arr 文件Arr
 @param type 1为模型文件、2为平面图文件
 @return 为true时表示存在
 */
+(NSMutableArray *)checkFileArr:(NSArray *)arr andType:(NSInteger)type andProjectId:(NSNumber *)projectId
{
    NSMutableArray *needDownArr = [[NSMutableArray alloc] init];
    
    if (arr == nil) {
        return needDownArr;
    }
    
    NSInteger arrCount = arr.count;
    
    NSString *folderPath = [FileUtil getModelFileAddress:[projectId integerValue] WithType:type];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSMutableArray *needDeleteArr = [[NSMutableArray alloc] initWithArray:[fileManager contentsOfDirectoryAtPath:folderPath error:nil]];
    
    for (int i = 0; i<arrCount; i++) {
        NSDictionary *dic = [arr objectAtIndex:i];
        NSString *file;
        if (type == 1) {
            file = [[dic[@"Path"] lastPathComponent] stringByDeletingPathExtension];
        }
        else
        {
            file = [dic[@"Path"] lastPathComponent];
        }
        
        [needDeleteArr removeObject:file];
        
        NSString *fullPath = [folderPath stringByAppendingPathComponent:file];
        
        if(![fileManager fileExistsAtPath:fullPath])
        {
            [needDownArr addObject:dic];
        }
    }
    
    if ([needDeleteArr containsObject:@"viewPoint.json"]) {
        [needDeleteArr removeObject:@"viewPoint.json"];
    }
    
    NSInteger deleteCount = needDeleteArr.count;
    for (int i = 0; i<deleteCount; i++) {
        NSString *fullPath = [folderPath stringByAppendingPathComponent:needDeleteArr[i]];
        [fileManager removeItemAtPath:fullPath error:nil];
    }
    
    return needDownArr;
}

@end
